import Layout from '../components/layout/common-layout.vue'
import External from '../components/external-sites/external-sites.vue'
// 从菜单中获取路由表
export const fetchRoutesFromMenu = (menuData, router) => {
  if (menuData.length > 0) {
    // 动态生成路由
    const userRoutes = []
    menuData.map(m => {
      const hasChildren = m.children && m.children.length
      if (!m.viewUrl && !hasChildren) {
        return
      }
      const newRoute = {
        path: hasChildren ? m.viewUrl : '/',
        name: hasChildren ? m.resourceName : '',
        meta: {
          title: hasChildren ? m.resourceName : ''
        }
      }

      if (hasChildren) {
        newRoute.component = Layout
        newRoute.children = []
        m.children.map(child => {
          if (child.children && child.children.length) {
            fetchRoutesFromMenu(child.children, router)
          } else {
            const isExternal = child.viewUrl.startsWith('http')
            let component = ''
            if (isExternal) {
              component = External
            } else {
              component = resolve => require([`@/views${child.viewComponent}.vue`], resolve)
            }
            newRoute.children.push({
              path: isExternal ? 'externalSite' : child.viewUrl,
              name: child.resourceName,
              meta: {
                title: child.resourceName
              },
              component: component
            })
          }
        })
      } else {
        const isExternal = m.viewUrl.startsWith('http')
        let component = ''
        if (isExternal) {
          component = External
        } else {
          component = resolve => require([`@/views${m.viewComponent}.vue`], resolve)
        }

        newRoute.component = Layout
        newRoute.children = [].concat({
          path: isExternal ? 'externalSite' : m.viewUrl,
          name: m.resourceName,
          meta: {
            title: m.resourceName
          },
          component: component
        })
      }
      userRoutes.push(newRoute)
    })
    router.options.routes.push(...userRoutes)
    router.addRoutes(userRoutes)
  }
}
